import sys
import numpy as np
import pyqtgraph as pg
import pyqtgraph.opengl as gl
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout


class PointCloudViewer(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle('点云查看器')
        self.setGeometry(100, 100, 800, 600)

        layout = QVBoxLayout()

        # 创建3D视图窗口
        self.view = gl.GLViewWidget()
        self.view.setCameraPosition(distance=50)

        # 添加网格
        grid = gl.GLGridItem()
        grid.scale(10, 10, 10)
        self.view.addItem(grid)

        # 生成示例点云数据
        n_points = 10000
        pos = np.random.randn(n_points, 3) * 10
        colors = np.random.rand(n_points, 4)
        colors[:, 3] = 1.0  # alpha通道

        # 创建点云对象
        self.scatter = gl.GLScatterPlotItem(
            pos=pos,
            color=colors,
            size=2,
            pxMode=True  # 像素模式，点的大小不随缩放改变
        )
        self.view.addItem(self.scatter)

        layout.addWidget(self.view)
        self.setLayout(layout)

    def update_point_cloud(self, points, colors=None):
        """更新点云数据"""
        if colors is None:
            colors = np.ones((len(points), 4))
            colors[:, :3] = [0.5, 0.5, 1.0]  # 默认蓝色

        self.scatter.setData(pos=points, color=colors)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    viewer = PointCloudViewer()
    viewer.show()
    sys.exit(app.exec_())